package ua.com.toltec.flymodemanager;

import java.util.Map;

import ua.com.toltec.flymodemanager.R;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.IBinder;
import android.os.Messenger;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.util.Log;
import android.widget.TimePicker;

public class ServiceActivity extends PreferenceActivity implements
		OnPreferenceChangeListener {

	static final int TIME_DIALOG_ID = 0;
	protected String mKey;

	private ServiceConnection mConnection = new ServiceConnection() {
		private Messenger mService;

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			mService = new Messenger(service);
		}

		@Override
		public void onServiceDisconnected(ComponentName name) {
			mService = null;
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			setSummary(mKey, String.format("%02d:%02d", hourOfDay, minute));
			setValue(mKey, String.format("%02d:%02d", hourOfDay, minute));
			stopService(new Intent(getApplicationContext(), ServiceAirplaneMode.class));
			startService(new Intent(getApplicationContext(), ServiceAirplaneMode.class));
//			PreferenceUnit pr = new PreferenceUnit(getApplicationContext());
//			Toast.makeText(getApplicationContext(), Long.toString(pr.getNextInterval()), Toast.LENGTH_SHORT);
		}
	};

	private int mHour;
	private int mMinute;
	private TimePickerDialog tpDialog = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		addPreferencesFromResource(R.layout.main);

		setPreferenceChange();
		setSummaryAll();

	}

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {

		if (preference.getKey().equals(Constants.STARTSERVICE)) {
			if ((Boolean) newValue) {
				startService(new Intent(this, ServiceAirplaneMode.class));
			} else {
				stopService(new Intent(this, ServiceAirplaneMode.class));
			}
		}

		if (preference.getKey().equals(Constants.FLYMODE)) {
			RadioServiceUnit.setAirplaneMode(this, (Boolean) newValue);
		}

		setSummary(preference.getKey(), newValue);
		return true;
	}

	private void setSummaryAll() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		Map<String, ?> pref = prefs.getAll();

		for (Map.Entry<String, ?> entry : pref.entrySet()) {
			Preference p = (Preference) this.findPreference(entry.getKey());
			if (p != null) {
				setSummary(entry.getKey(), entry.getValue().toString());
			}
		}

	}

	private void setSummary(String key, Object newValue) {
		this.findPreference(key);

		try {
			setSummaryPreference(key, newValue.toString());
		} catch (Exception e) {
			Log.e(key + "  " + newValue.toString(), e.getMessage());
		}
	}

	private void setValue(String key, Object newValue) {
		SharedPreferences myPreferences = PreferenceManager
				.getDefaultSharedPreferences(getApplicationContext());
		SharedPreferences.Editor myPreferencesEditor = myPreferences.edit();
		myPreferencesEditor.putString(key, newValue.toString());
		myPreferencesEditor.commit();
	}

	private void setPreferenceChange() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);

		Map<String, ?> pref = prefs.getAll();

		for (Map.Entry<String, ?> entry : pref.entrySet()) {
			Preference p = (Preference) this.findPreference(entry.getKey());
			if (p != null) {
				try {
					p.setOnPreferenceChangeListener(this);
				} catch (Exception e) {
					// Log.e("", e.getMessage());
				}
			}
		}
	}

	private void setSummaryPreference(String name, String summary) {
		this.findPreference(name).setSummary(summary);
	}

	public boolean isServiceRunning() {
		Log.d("", ServiceAirplaneMode.class.getName());
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
		for (RunningServiceInfo service : manager
				.getRunningServices(Integer.MAX_VALUE)) {
			if (ServiceAirplaneMode.class.getName().equals(
					service.service.getClassName())) {
				return true;
			}
		}
		return false;
	}

	protected void getTimeFromPreference() {
		SharedPreferences prefs = PreferenceManager
				.getDefaultSharedPreferences(this);
		String strTime = prefs.getString(mKey, "00:00");
		try {
			mHour = Math.min(23, Integer.parseInt(strTime.substring(0, 2)));
		} catch (Exception e) {
			mHour = 0;
		}
		try {
			mMinute = Math.min(59, Integer.parseInt(strTime.substring(3, 5)));
		} catch (Exception e) {
			mMinute = 0;
		}

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		if (mKey!=null) {
			switch (id) {
			case TIME_DIALOG_ID:
				if (mKey.equals(Constants.FLYMODEON)
						|| mKey.equals(Constants.FLYMODEOFF)) {
					getTimeFromPreference();
					tpDialog = new TimePickerDialog(this, mTimeSetListener, mHour,
							mMinute, true);
					return tpDialog;
				}
			}
		}
		return null;
	}

	@Override
	public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
			Preference preference) {
		mKey = preference.getKey();
		if (mKey.equals(Constants.FLYMODEON)
				|| mKey.equals(Constants.FLYMODEOFF)) {
			getTimeFromPreference();
			if (tpDialog != null) {
				tpDialog.updateTime(mHour, mMinute);
			}
			showDialog(TIME_DIALOG_ID);
		}

		return super.onPreferenceTreeClick(preferenceScreen, preference);
	}

}
